package com.fenghuaxz.rpcframework;

import com.fenghuaxz.rpcframework.model.MsgCallback;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 创建 : 七羽软件工作室
 * 时间 : 2017/9/28 : 2:20
 */
public class BroadcastContext {

    public final ChannelGroup group = new IChannelGroup(GlobalEventExecutor.INSTANCE);
    protected final ConcurrentMap<String,MsgCallback> callbacks = new ConcurrentHashMap<>();

    public MessagePacket newPacket(){
        return this.newPacket((Channel[]) null);
    }

    public MessagePacket newPacket(Channel... channel){
        Channel[] cache = channel != null && channel.length != 0 ? channel : group.toArray(new Channel[group.size()]);
        return new MessagePacket(this,cache);
    }

    public MessagePacket newPacket(String... channelId){
        return this.newPacket(findChannel(channelId));
    }

    private final Channel[] findChannel(String... channelId){
        List<Channel> cache = new ArrayList<>();
        for (String idStr : channelId){
            Channel channel = ((IChannelGroup)group).find(idStr);
            if (channel != null) cache.add(channel);
        }
        return cache.toArray(new Channel[cache.size()]);
    }
}
